<script setup lang="ts">
import store from '@/store'
import { numberToChinese } from '@/utils/tools'
import { createVNode, h, reactive, ref, nextTick } from 'vue'
import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import IconFont from '@/components/IconFont/index.vue'
import VisibleRender from '@/components/VisibleRender.vue'
import draggable from 'vuedraggable'
import { typeOf } from '@/utils/tools'

const modal = reactive({
  open: false,
  type: 'save',
  allowUpdate: true,
  loading: false,
  title: '新建问卷'
})

const formState = reactive({
  id: '',
  questionnaireName: '',
  questionnaireType: 'scale',
  content: [
    {
      name: '',
      id: 'A',
      list: [
        {
          name: '',
          id: 'A-1',
          type: '单选',
          sort: '',
          value: '',
          inputText: '',
          inputMode: '',
          rules: null,
          config: null,
          options: [
            {
              id: 0,
              score: 0,
              value: '',
              input: false,
              maxlength: 50,
              exclusive: false
            }
          ],
          exc: ''
        }
      ]
    }
  ]
})

const answertype = [
  {
    label: '单选',
    value: '单选'
  },
  {
    label: '多选',
    value: '多选'
  },
  {
    label: '输入',
    value: '输入'
  },
  {
    label: '单选+输入',
    value: '单选+输入'
  },
  {
    label: '多选+输入',
    value: '多选+输入'
  },
  {
    label: '数字选择',
    value: '数字选择'
  },
  {
    label: '搜索输入',
    value: '搜索输入'
  }
]

const formState_reset = (item) => {
  Object.assign(formState, {
    id: '',
    questionnaireName: '',
    questionnaireType: 'scale',
    content: []
  })
  nextTick(() => {
    if (item) {
      Object.assign(formState, item)
    } else {
      Object.assign(formState, {
        id: '',
        questionnaireName: '',
        questionnaireType: 'scale',
        content: [
          {
            name: '',
            id: 'A',
            list: [
              {
                name: '',
                id: 'A-1',
                type: '单选',
                sort: '',
                value: '',
                inputText: '',
                inputMode: '',
                rules: null,
                config: null,
                options: [
                  {
                    id: 0,
                    score: 0,
                    value: '',
                    input: false,
                    maxlength: 50,
                    exclusive: false
                  }
                ],
                exc: ''
              }
            ]
          }
        ]
      })
    }
  })
}

const subitemTypeChange = (e, item) => {
  if (e === '输入' || !e) {
    item.options = []
  } else {
    item.options = [
      {
        id: 0,
        score: 0,
        value: '',
        input: false,
        maxlength: 50,
        exclusive: false
      }
    ]
  }
  if (e === '数字选择') {
    item.config = {
      min: '',
      max: '',
      min_label: '',
      max_label: ''
    }
  } else if (e === '搜索输入') {
    item.config = {
      url: '',
      type: 'inner'
    }
  } else {
    item.config = null
  }
}

const moveOptions = (list, item) => {
  console.log('拖拽结束')
}

const del = (index, item) => {
  item.splice(index, 1)
}

const delTwo = (index, item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确认是否删除',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      item.splice(index, 1)
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const changes = (index, item, num) => {
  //   console.log(item[index].score)
  const regex = /^([0-9]|[1-9]\d|99)$/
  if (!regex.test(item[index].score)) {
    // 如果输入值不符合规定的1到99的整数，则将inputValue重置为上一个合法的值
    if (Number(item[index].score) > 99) {
      item[index].score = 99
    } else {
      item[index].score = 0
    }
    // item[index].score = item[index].score.substring(0, item[index].score.length - 1)
    // item[index].score = 0
  } else {
    // 如果输入值符合规定的1到99的整数，则更新inputValue
    item[index].score = item[index].score
  }
}
const addOptions = (item) => {
  const indexs = item.map((v) => {
    return v.id
  })
  let i = 0
  while (indexs.includes(i)) {
    i++
  }
  console.log(i)

  item.push({
    id: i,
    score: 0,
    value: '',
    input: false,
    maxlength: 50
  })
}

const elementChecked = (value, i, subitem) => {
  subitem.options.map((v, index) => {
    if (i === index) {
      if (value) {
        v.value = '其他'
        v.disabled = true
        v.input = true
      } else {
        v.value = ''
        v.disabled = false
        v.input = false
      }
    } else {
      if (v.disabled) {
        v.value = ''
      }
      v.disabled = false
      v.input = false
    }
  })
}

const addSubitem = (module) => {
  console.log(module)
  let index = 1
  while (module.list.some((v) => v.id === module.id + '-' + index)) {
    index++
  }
  console.log(module.id + '-' + index)
  module.list.push({
    name: '',
    id: module.id + '-' + index,
    type: '单选',
    sort: '',
    value: '',
    inputText: '',
    inputMode: '',
    rules: null,
    config: null,
    options: [
      {
        id: 0,
        score: 0,
        value: '',
        input: false,
        maxlength: 50,
        exclusive: false
      }
    ],
    exc: ''
  })
}

const sorts = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
]

const addModule = () => {
  let index = 0
  while (formState.content.some((v) => v.id === sorts[index])) {
    index++
  }
  console.log(sorts[index])

  formState.content.push({
    name: '',
    id: sorts[index],
    list: [
      {
        name: '',
        id: sorts[index] + '-1',
        type: '单选',
        sort: '',
        value: '',
        inputText: '',
        inputMode: '',
        rules: null,
        config: null,
        options: [
          {
            id: 0,
            score: 0,
            value: '',
            input: false,
            maxlength: 50,
            exclusive: false
          }
        ],
        exc: ''
      }
    ]
  })
}

const subitem_check = async (_, value) => {
  if (value.type) {
    if (!value.name) {
      return Promise.reject('请输入问题描述')
    }
    if (['单选', '单选+输入', '多选', '多选+输入'].includes(value.type)) {
      const f = value.options.some((v) => {
        return v.value
      })
      if (!f) {
        return Promise.reject('请完善至少一个问题选项')
      }
      if (value.type.includes('+输入')) {
        const f2 = value.options.some((v) => {
          return v.input
        })
        if (!f2) {
          return Promise.reject('添加输入框需勾选')
        }
      }
    }
  } else {
    return Promise.reject('请选择问题类型')
  }
  return
}

const modelForm = ref(null)

const init = (item) => {
  modelForm.value?.clearValidate()
  if (item) {
    formState_reset(item)
    modal.title = '编辑问卷'
    modal.type = 'update'
    modal.open = true
  } else {
    formState_reset()
    modal.allowUpdate = true
    modal.title = '新建问卷'
    modal.type = 'save'
    modal.open = true
  }
}

const modalConfirm = () => {
  modelForm.value
    .validate()
    .then(() => {
      modal.loading = true

      console.log(formState.content)
      formState.content.map((v) => {
        v.list.map((u) => {
          if (u.type === '数字选择') {
            if (typeOf(u.config.min) === 'string') {
              u.config.min = parseInt(u.config.min)
            }
            if (typeOf(u.config.max) === 'string') {
              u.config.max = parseInt(u.config.max)
            }
          }
        })
      })

      emit('onConfirm', {
        data: formState,
        success: () => {
          console.log('success')
          modal.loading = false
          modal.open = false
        },
        fail: () => {
          console.log('fail')
          modal.loading = false
        },
        type: modal.type
      })
    })
    .catch((e) => {
      console.log(e)
      modelForm.value.scrollToField(e.errorFields[0].name, {
        behavior: 'smooth',
        block: 'center'
      })
    })
}

const emit = defineEmits(['onConfirm'])

defineExpose({
  init
})
</script>

<template>
  <a-modal
    width="720px"
    :bodyStyle="store.userStore.bodyStyle"
    v-model:open="modal.open"
    :title="modal.title"
    ok-text="确认"
    cancel-text="取消"
    @ok="modalConfirm"
    :maskClosable="false"
  >
    <a-form
      class="modelForm"
      ref="modelForm"
      :colon="false"
      :model="formState"
      :label-col="{ style: { width: '80px' } }"
      labelAlign="left"
    >
      <a-form-item label="模板类型" name="questionnaireType" required>
        <a-select v-model:value="formState.questionnaireType">
          <a-select-option label="量表问卷" value="scale"> 量表问卷 </a-select-option>
          <a-select-option label="普通问卷" value="normal"> 普通问卷 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="健康随访名称"
        :label-col="{ style: { width: '110px' } }"
        name="questionnaireName"
        required
        :rules="{
          required: true,
          message: '健康随访名称不能为空',
          trigger: 'change',
          whitespace: true
        }"
      >
        <a-input
          style="width: 350px"
          v-model:value="formState.questionnaireName"
          autocomplete="off"
          :maxlength="50"
          placeholder="请输入健康随访名称"
        />
      </a-form-item>
      <a-form-item>
        <a-row class="title">
          <a-col :span="24"> 健康随访内容 </a-col>
        </a-row>
      </a-form-item>
      <template v-for="(module, index) in formState.content" :key="index">
        <a-form-item
          :label="'模块' + numberToChinese(index + 1)"
          required
          :name="['content', index, 'name']"
          :rules="{
            required: true,
            message: '模块名不能为空',
            trigger: 'change'
          }"
        >
          <a-row>
            <a-col :span="24" class="row">
              <a-input
                v-model:value="module.name"
                autocomplete="off"
                :maxlength="50"
                placeholder="请输入模块名称"
              />
              <a-button v-if="index" type="link" danger @click="delTwo(index, formState.content)"
                >删除模块</a-button
              >
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item
          v-for="(subitem, i) in module.list"
          :key="i"
          :name="['content', index, 'list', i]"
          :rules="{
            validator: subitem_check
          }"
          class="questionItem"
        >
          <visible-render height="100px">
            <a-row class="row">
              <a-col :span="8">
                <a-form-item
                  :label="'问题 ' + Number(i + 1)"
                  :label-col="{ style: { width: '80px' } }"
                >
                  <a-select
                    v-model:value="subitem.type"
                    @change="subitemTypeChange($event, subitem)"
                    style="width: 120px"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                  >
                    <a-select-option
                      v-for="item in answertype"
                      :key="item.value"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="15">
                <a-row>
                  <a-col :span="11" v-if="subitem.type === '输入'">
                    <a-form-item label="input类型">
                      <a-select style="width: 100px" v-model:value="subitem.inputMode">
                        <a-select-option value="text">文本键盘</a-select-option>
                        <a-select-option value="number">整数键盘</a-select-option>
                        <a-select-option value="idcard">身份证键盘</a-select-option>
                        <a-select-option value="digit">小数点键盘</a-select-option>
                        <a-select-option value="tel">电话键盘</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="13">
                    <a-form-item label="额外参数">
                      <a-input
                        style="width: 140px"
                        v-model:value="subitem.exc"
                        autocomplete="off"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col class="ft" span="1">
                <icon-font
                  v-if="i"
                  style="margin: 0 16px"
                  class="icon icon-del point"
                  type="icon-shanchu"
                  @click="del(i, module.list)"
                />
              </a-col>
            </a-row>
            <a-form-item>
              <a-row>
                <a-col :span="24" class="row">
                  <a-textarea
                    style="margin: 0 16px; width: 100%"
                    v-model:value="subitem.name"
                    placeholder="请输入问题描述"
                    :maxlength="500"
                    :rows="2"
                  />
                </a-col>
              </a-row>
            </a-form-item>
            <template v-if="['单选', '单选+输入', '多选', '多选+输入'].includes(subitem.type)">
              <a-form-item>
                <draggable
                  class="drag"
                  :list="subitem.options"
                  :handle="'.icon-move'"
                  itemKey="id"
                  animation="300"
                  @end="moveOptions($event, subitem)"
                >
                  <template #item="{ element, index }">
                    <a-row class="item row" :gutter="[16, 0]">
                      <a-col>
                        <a-input
                          style="width: 200px"
                          v-model:value="element.value"
                          autocomplete="off"
                          :maxlength="50"
                          :disabled="element.disabled"
                          placeholder="请输入选项描述"
                        />
                      </a-col>
                      <a-col>
                        <icon-font class="icon-move" type="icon-yidong" />
                      </a-col>
                      <a-col class="row">
                        <span>计分：</span>
                        <a-input-number
                          style="width: 60px; display: inline-block; vertical-align: middle"
                          v-model:value="element.score"
                          :min="0"
                          :max="100"
                          type="Number"
                          @input="changes(index, subitem.options, handleChange)"
                          @change="changes(index, subitem.options, handleChange)"
                        />
                        <!-- <a-input
                            style="width: 100px"
                            v-model:value="element.score"
                            type="Number"
                            @input="changes(index, subitem.options, handleChange)"
                            @change="changes(index, subitem.options, handleChange)"
                            placeholder="请输入分数"
                          ></a-input> -->
                      </a-col>
                      <a-col class="row" v-if="subitem.type.includes('+输入')">
                        输入框：
                        <a-switch
                          v-model:checked="element.input"
                          @change="elementChecked($event, index, subitem)"
                          checked-children="是"
                          un-checked-children="否"
                        />
                      </a-col>
                      <a-col class="row" v-if="subitem.type.includes('多选')">
                        排他：
                        <a-switch
                          v-model:checked="element.exclusive"
                          checked-children="是"
                          un-checked-children="否"
                        />
                      </a-col>
                      <a-col class="row" style="flex: 1; flex-direction: row-reverse">
                        <icon-font
                          v-if="index"
                          class="icon-del"
                          type="icon-shanchu"
                          @click="del(index, subitem.options)"
                        />
                        <icon-font
                          v-else
                          class="icon-plus"
                          type="icon-xinzeng"
                          @click="addOptions(subitem.options)"
                        />
                      </a-col>
                    </a-row>
                  </template>
                </draggable>
              </a-form-item>
            </template>
            <template v-else-if="subitem.type === '数字选择'">
              <a-row class="config" :gutter="[16, 0]">
                <a-col :span="12">
                  <a-form-item
                    :name="['content', index, 'list', i, 'config', 'min']"
                    :rules="{
                      required: true,
                      message: '最小值不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      :value="subitem.config.min"
                      autocomplete="off"
                      @input="(e) => (subitem.config.min = e.target.value.replace(/[^0-9]/g, ''))"
                      placeholder="最小值(包含)"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :name="['content', index, 'list', i, 'config', 'max']"
                    :rules="{
                      required: true,
                      message: '最大值不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      :value="subitem.config.max"
                      autocomplete="off"
                      @input="(e) => (subitem.config.max = e.target.value.replace(/[^0-9]/g, ''))"
                      placeholder="最大值(不含)"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item>
                    <a-input
                      v-model:value="subitem.config.min_label"
                      autocomplete="off"
                      placeholder="最小值文案"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item>
                    <a-input
                      v-model:value="subitem.config.max_label"
                      autocomplete="off"
                      placeholder="最大值文案"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </template>
            <template v-else-if="subitem.type === '搜索输入'">
              <a-row class="config" :gutter="[16, 0]">
                <a-col>
                  <a-form-item>
                    <a-select style="width: 100px" v-model:value="subitem.config.type">
                      <a-select-option value="inner">内链</a-select-option>
                      <a-select-option value="outside">外链</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :name="['content', index, 'list', i, 'config', 'url']"
                    :rules="{
                      required: true,
                      message: '请求地址不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      style="width: 100%"
                      v-model:value="subitem.config.url"
                      autocomplete="off"
                      placeholder="请求地址"
                    />
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="12">
                  <a-form-item
                    :name="['content', index, 'list', i, 'config', 'key']"
                    :rules="{
                      required: true,
                      message: '请求参数名不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      v-model:value="subitem.config.key"
                      autocomplete="off"
                      placeholder="参数名"
                    />
                  </a-form-item>
                </a-col> -->
              </a-row>
            </template>
          </visible-render>
        </a-form-item>
        <a-form-item style="margin-top: -16px">
          <a-button type="link" :icon="h(PlusOutlined)" @click="addSubitem(module)"
            >新增问题</a-button
          >
        </a-form-item>
      </template>
      <a-form-item>
        <a-row class="title">
          <a-button class="add" :icon="h(PlusOutlined)" @click="addModule">添加模块</a-button>
        </a-row>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less">
.modelForm {
  .red {
    color: #f56667;
  }
  .ant-form-item {
    margin-bottom: 15px;
    &.questionItem {
      margin-bottom: 16px;
      padding-top: 8px;
      // background: #f7f8fa;
    }
  }

  .title {
    width: 100%;
    height: 32px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 500;
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 500;
    // color: #1d2129;
    line-height: 24px;
  }
  .add {
    width: 648px;
    height: 32px;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 400;
    color: #165dff;
    line-height: 22px;
    margin: 0 12px;
  }
  .icon-plus,
  .icon-del {
    font-size: 16px;
  }
  .icon-plus {
    color: #165dff;
  }
  .icon-del {
    color: #f53f3f;
  }
  .icon-move {
    color: #4e5969;
    font-size: 24px;
    line-height: 32px;
    cursor: move;
  }
  .form-item {
    line-height: 32px;
  }
}
.row {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.drag {
  padding: 0 16px;
  .item:not(:first-child) {
    margin-top: 8px;
  }
}
.config {
  padding: 0 16px;
}
.point {
  cursor: pointer;
}
.row {
  .ft {
    height: 47px;
    display: flex;
    flex-direction: row-reverse;
    align-items: flex-start;
    .icon {
      line-height: 32px;
      height: 32px;
    }
  }
}
</style>
